pub mod serial_server;
pub mod mqtt_server;
pub mod control_service;

use std::fs;
use std::path::Path;
use fast_log::consts::LogSize;
use fast_log::plugin::file_split::RollingType;
use log::Level;
use crate::common::constant;
use envmnt::types::EnvmntResult;
use crate::common::cs;
use fast_log::plugin::packer::ZipPacker;
use crate::base;

/// 全局初始化
pub async fn init() -> cs::Result<()>
{
    //mac
    println!(" - mac address : `{}`", base::mac_address());
    //env
    init_env()?;
    //log
    init_log(envmnt::is_or(constant::LOG_DEBUG, false))?;
    //serial port
    serial_server::init_serial_port(
        base::scheduled(),
        envmnt::is("DATABASE_TRUNCATE"),
        base::serial_config(),
    ).await?;
    //mqtt
    mqtt_server::init_mqtt().await?;
    println!(" - init complete");
    Ok(())
}

/// 初始化全局变量
fn init_env() -> EnvmntResult<()>
{ envmnt::load_file(constant::ENV_PATH) }

/// 初始化日志
fn init_log(debug: bool) -> cs::Result<()>
{
    let path = Path::new("logs/");
    if !path.exists() {
        fs::create_dir("logs/").unwrap();
    }
    let level = if debug { Level::Debug } else { Level::Info };
    fast_log::init_split_log(
        "logs/",
        1000,
        LogSize::MB(1),
        false,
        RollingType::All,
        level,
        None,
        Box::from(ZipPacker {}),
        true,
    )?;
    Ok(())
}
